package org.example.myleet.Utils;

import java.util.LinkedList;
import java.util.Queue;

public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode() {
    }

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("TreeNode{");
        sb.append("val=").append(val);
        sb.append('}');
        return sb.toString();
    }

    public String serialize() {
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(this);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; ++i) {
                TreeNode node = queue.poll();
                if (-1 == node.val) {
                    sb.append("null").append(',');
                    continue;
                } else {
                    sb.append(node.val).append(',');
                }
                if (null == node.left) {
                    queue.add(new TreeNode(-1));
                } else {
                    queue.add(node.left);
                }
                if (null == node.right) {
                    queue.add(new TreeNode(-1));
                } else {
                    queue.add(node.right);
                }
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        while (sb.length() >= 5 && ",null".equals(sb.substring(sb.length() - 5))) {
            sb.delete(sb.length() - 5, sb.length());
        }
        sb.append(']');
        return sb.toString();
    }
}
